﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Assets.Scripts.TDuResource;
using UnityEngine;
using Pvr_UnitySDKAPI;
//using UnityEngine.UI;

namespace Assets.Scripts.TDu3DWork
{
    class TDuSceneWorker : TDuSceneBaseWorker
    {
        public string m_strCurStepName;
        public double m_dOffsetFrame;
        public string m_strCurPlayingVar;
        public double m_dStartTime = 0;
        public string m_strCurHilightStep;

        public bool m_bPlaying;
        public bool m_bOtherStepRun;
        public List<HighlightableObject> m_listHighObj;

        protected Vector3 m_v3MainCanvasPos;
        protected Vector3 m_v3PopupCanvasPos;

        public TDuSceneWorker(string strCfgUrl) : base(strCfgUrl)
        {
            m_dStartTime = 0;
            m_dOffsetFrame = 0;
            m_bOtherStepRun = true;

            m_strCurStepName = "";
            m_strCurHilightStep = "";
            m_strCurPlayingVar = "";
            m_listHighObj = new List<HighlightableObject>();
            //isHasController = false;
        }

        public TDuSceneWorker(){
            m_dStartTime = 0;
            m_dOffsetFrame = 0;
            m_bOtherStepRun = true;
            m_v3MainCanvasPos = new Vector3();
            m_v3PopupCanvasPos = new Vector3();

            m_strCurStepName = "";
            m_strCurHilightStep = "";
            m_strCurPlayingVar = "";
            m_listHighObj = new List<HighlightableObject>();
        }

        public void running()
        {
            if (m_bPlaying)
            {
                //使用时间检测
                m_dStartTime += Time.deltaTime;
                //Debug.Log("【OutputInfo】----[Update] 累计帧数时间:" + m_dStartTime + "," + "某一步动画时间:" + m_dOffsetFrame);

                if (m_dStartTime - m_dOffsetFrame < 0.1)
                {
                    return;
                }
                m_dStartTime = 0;
                
                if (m_sceneCfg.vecVariableNode.ContainsKey(m_strCurPlayingVar))//
                {
                    VariableNode curVarNode = m_sceneCfg.vecVariableNode[m_strCurPlayingVar];
                    m_bPlaying = false;
                    if (!curVarNode.bVarRandom)
                    {
                        if (m_sceneCfg.sceneProperty.nHintPos == 0)
                        {

                            //影藏激活物体的高亮
                            offActiveObj(curVarNode.setActiveObj);

                            //搜索下一步，并通过激活物体提示
                            string strAudio = "";
                            string strText = "";

                            if (searchNextStep(strAudio, strText))
                            {
                                if (strAudio.Length > 0)
                                {
                                    //播放声音
                                    m_audioPlayer.PlayAudio(curVarNode.strVarAudio);
                                }

                                if (strText.Length > 0)
                                {
                                    m_uiManager.updateMainNavigatorTipText(curVarNode.strVarText);
                                    //m_uiManager.updateTipTextDashboard(curVarNode, m_popupCanvas);
                                }
                                
                            }

                        }
                        if(curVarNode.strVarText.Length > 0)
                        {
                            m_uiManager.updateMainNavigatorTipText(curVarNode.strVarText);
                        }
                          
                        if (curVarNode.strVarAudio.Length > 0)
                        {
                            m_audioPlayer.PlayAudio(curVarNode.strVarAudio);
                            //播放声音
                        }
                     

                        //改变视点
                        if( !m_bIsVR )
                            setViewPort(curVarNode.strVarViewport);

                        for (int i = 0; i < curVarNode.arrCondition.Count; i++)
                        {
                            if (curVarNode.arrCondition[i].bSync == false)
                            {
                                if (m_sceneCfg.vecVariableNode.ContainsKey(curVarNode.arrCondition[i].strName))
                                {
                                    VariableNode conVarNode = m_sceneCfg.vecVariableNode[curVarNode.arrCondition[i].strName];
                                    if (curVarNode.arrCondition[i].bJump == false && (conVarNode.strVarNodeType == "Step" || conVarNode.strVarNodeType == "Assemble"))
                                    {
                                        if (curVarNode.arrCondition[i].cDestValue.dValue < 0.5)
                                        {
                                            updateVarState(curVarNode.arrCondition[i].strName, 0, 0);
                                        }
                                        else
                                        {
                                            scrollStepVar(conVarNode, true);
                                        }
                                    }
                                    else
                                    {
                                        TDuPostEventArgs postArgs = new TDuPostEventArgs();
                                        postArgs.getPostActionType(conVarNode.strVarNodeType);
                                        postArgs.m_varNode = conVarNode;
                                        onPostAction(postArgs);
                                    }
                                }
                            }
                        }
                    }
                }

                //仿真;
            }
        }
        public void lateRunning()
        {
            //监视鼠标左键按下状态;
            if (Input.GetMouseButton(0)/* && !getVROr3D()*/)
            {
                TDuPostEventArgs postArgs = new TDuPostEventArgs();
                postArgs.getPostActionType("MouseRayCast");
                onPostAction(postArgs);
            }

            //监控VR设备;
            if (getVROr3D())
            {
                if (m_headSet != null)
                {
                    TDuVRControllerEventArgs vrControllerArgs = new TDuVRControllerEventArgs();
                    vrControllerArgs.getVRControllerCmd();
                    onVRControllerAction(vrControllerArgs);
                }
            }


            //跟随手柄;
            if (m_currentController && m_mainCanvas)
            {

                if (m_currentController == m_controller0)
                {
                    //m_mainCanvas跟随手柄
                    Transform m_v3MainCanvasPosPoint = m_controller1.transform.Find("MainCanvasPosPoint"); /*m_v3MainCanvasPosPoint*/
                    m_v3MainCanvasPos = m_v3MainCanvasPosPoint.transform.position;
                    m_mainCanvas.transform.rotation = m_v3MainCanvasPosPoint.transform.rotation;


                }
                else if (m_currentController == m_controller1)
                {
                    //Debug.Log("");
                    //Transform m_v3MainCanvasPosPoint = m_controller0.transform.Find("m_v3MainCanvasPosPoint"); /*m_v3MainCanvasPosPoint*/
                    //m_v3MainCanvasPos.x = m_v3MainCanvasPosPoint.transform.position.x;
                    //m_v3MainCanvasPos.y = m_v3MainCanvasPosPoint.transform.position.y + 0.25f;
                    //m_v3MainCanvasPos.z = m_v3MainCanvasPosPoint.transform.position.z - 0.2f;
                    //m_mainCanvas.transform.rotation = m_v3MainCanvasPosPoint.transform.rotation;
                    //m_v3MainCanvasPos.x = m_controller0.transform.position.x;
                    //m_v3MainCanvasPos.y = m_controller0.transform.position.y + 0.25f;
                    //m_v3MainCanvasPos.z = m_controller0.transform.position.z - 0.2f;
                    //m_mainCanvas.transform.rotation = m_controller0.transform.rotation;
                }
                m_mainCanvas.transform.position = m_v3MainCanvasPos;

                /*
                Vector3 pos = m_headSet.transform.position + m_headSet.transform.forward * 0.5f;
                Quaternion q2 = Quaternion.LookRotation(m_headSet.transform.forward);
                m_mainCanvas.transform.position = new Vector3(pos.x, 5, pos.z);
                m_mainCanvas.transform.rotation = new Quaternion(0, q2.y, 0, q2.w); 
                */
            }

            //跟随眼镜
            if (m_headSet && m_popupCanvas)
            {
                Transform m_v3PopupCanvasPosPoint = m_headSet.transform.Find("PopupCanvasPosPoint"); /*m_v3MainCanvasPosPoint*/
                m_v3PopupCanvasPos = m_v3PopupCanvasPosPoint.transform.position;
                m_popupCanvas.transform.rotation = m_v3PopupCanvasPosPoint.transform.rotation;

                m_popupCanvas.transform.position = m_v3PopupCanvasPos;
            }
        }

        public void updateMsgVar(string varName, bool bConfirm)
        {
            Debug.Log("【OutputInfo】----[updateMsgvar] cur varnode name:" + varName);
            m_strCurStepName = varName;

            if (m_sceneCfg.vecVariableNode.ContainsKey(varName) && bConfirm)
            {
                VariableNode m_curNode = m_sceneCfg.vecVariableNode[varName];                
                m_curNode.dVarCurValue += 1;
                if (m_curNode.dVarCurValue > m_curNode.dVarMaxValue)
                {
                    m_curNode.dVarCurValue = m_curNode.dVarMaxValue;
                }

                for (int i = 0; i < m_curNode.arrCondition.Count; i++)
                {
                    if (m_sceneCfg.vecVariableNode.ContainsKey(m_curNode.arrCondition[i].strName))
                    {
                        VariableNode conVarNode = m_sceneCfg.vecVariableNode[m_curNode.arrCondition[i].strName];
                        Debug.Log("【OutputInfo】----[updateMsgvar] cur varnode post var node name:" + conVarNode.strVarNodeName);

                        if (!m_curNode.arrCondition[i].bJump && (conVarNode.strVarNodeType == "Step" || conVarNode.strVarNodeType == "Assemble" ))
                        {
                            scrollStepVar(conVarNode);
                        }
                        else if (m_curNode.arrCondition[i].bJump)
                        {
                            conVarNode.dVarCurValue = m_curNode.arrCondition[i].cDestValue.value(m_sceneCfg.vecVariableNode);
                            continue;
                        }
                        else
                        {
                            updateVarState(m_curNode.arrCondition[i].strName, 0, 0);
                        }
                    }

                }
                if (m_curNode.strVarAudio.Length > 0)
                {
                    m_uiManager.updateMainNavigatorTipText(m_curNode.strVarText);
                    m_audioPlayer.PlayAudio(m_curNode.strVarAudio);
                }
            }
        }

        public void scrollStepVar(VariableNode varnode, bool bScore = false, bool bPlay = true)
        {
            Debug.Log("【OutputInfo】----[scrollStepVar] 执行的varnode name:" + varnode.strVarNodeName );
            if (varnode.strVarNodeType == "Step" || varnode.strVarNodeType == "Assemble" )
            {
                if (bPlay)
                {
                    if (!m_bPlaying)
                    {
                        varnode.dVarCurValue = varnode.dVarMinValue;
                        double dVarStartTime = varnode.getCurValueTime();
                        varnode.dVarCurValue = varnode.dVarMaxValue;
                        double dVarStopTime  = varnode.getCurValueTime();

                        m_bPlaying = true;
                        m_dOffsetFrame = (dVarStopTime - dVarStartTime) / m_sceneCfg.sceneAttr.nFPS;
                        m_strCurPlayingVar = varnode.strVarNodeName;
                        m_strCurStepName = varnode.strVarNodeName;

                        if (varnode.bVarRandom)//随机取值
                        {
                            m_uiManager.updateMainNavigatorTipText(varnode.strVarText);
                            m_audioPlayer.PlayAudio(varnode.strVarAudio);
                        }

                        Debug.Log("【OutputInfo】----[scrollStepVar] 执行的动画字符串:" + varnode.strVarNodeName);
                        /*
                        if (varnode.strVarNodeName != "")
                            m_animation.Play(varnode.strVarNodeName);
                        */
                        if (varnode.strVarNodeName != ""&& varnode.setAnimateObj!=null)
                          AnimationMgr.instance.PlayAni("Take 001", m_animation.gameObject, (float)varnode.dVarStartTime, (float)varnode.dVarStopTime);//播放)
                    }
                }
                else
                {
                    //TDuSceneTrigger.animation.Stop();
                    varnode.bComplete = bScore;
                }
            }
            else
            {
                {
                    m_strCurStepName = varnode.strVarNodeName;
                    
                }
            }
        }

        //变量状态更新
        public void updateVarState(string _strVarName, int _k, double _dDelt, double _dTime = 0, string _strTimerName = "", int _nLevel = 0)
        {
            if (m_sceneCfg.vecVariableNode.ContainsKey(_strVarName))
            {
                VariableNode varNode = m_sceneCfg.vecVariableNode[_strVarName];
                if (Math.Abs(varNode.dVarCurValue - _dDelt) < 1e-6)
                {
                    varNode.dVarCurValue = _k * (varNode.dVarMaxValue - varNode.dVarMinValue) + _dDelt;
                    //播放完后，需要将动画物体状态设置为当前变量值对应的状态？ 播放到指定帧
                }
            }
        }

        //搜索下一步的提示物体
        public bool searchNextStep(string strAudio, string strText)
        {
            Debug.Log("【OutputInfo】----[searchNextStep]当前执行的变量名:"   + m_strCurStepName);
            Debug.Log("【OutputInfo】----[searchNextStep]当前高亮的的变量名:" + m_strCurHilightStep);
            if (m_strCurStepName != "")
            {
                searchNextStep2(m_strCurStepName);
                return true;
            }
            
            bool bToFind = false;
            foreach (KeyValuePair<string, VariableNode> kv in m_sceneCfg.vecVariableNode)
            {
                if (kv.Value.strVarNodeName == m_strCurHilightStep)
                    bToFind = true;

                if (bToFind)
                {
                    VariableNode varnode = m_sceneCfg.vecVariableNode[m_strCurHilightStep];
                    if (((varnode.strVarNodeType == "Assemble") || (varnode.strVarNodeType == "Step")) &&
                    varnode.dVarCurValue < 0.5 && varnode.setActiveObj.Count > 0)
                    {
                        if (checkVarPreCondition(varnode.arrPreCondtion))
                        {
                            if (m_sceneCfg.sceneProperty.nHintPos != 3)
                            {
                                //显示激活物体;
                                showActiveObj(varnode.setActiveObj);

                                if (m_strCurHilightStep == varnode.strVarNodeName)
                                    return true;

                                //当前步骤名;
                                m_strCurHilightStep = varnode.strVarNodeName;
                                return true;
                            }
                        }
                        else
                            return false;
                    }
                    else if (varnode.strVarNodeType == "Rotation" && varnode.setActiveObj.Count > 0 &&
                                varnode.strVarText == "")
                    {
                        strAudio = varnode.strVarAudio;
                        strText = varnode.strVarText;

                        showActiveObj(varnode.setActiveObj);

                        if (m_strCurHilightStep == varnode.strVarNodeName)
                            return true;

                        m_strCurHilightStep = varnode.strVarNodeName;
                        return true;
                    }
                }
            }


            return false;

        }

        public bool searchNextStep2(string strActive)
        {
            //判断激活物体是否存在
            bool bToFind = false;
            m_strCurHilightStep = strActive;

            foreach (KeyValuePair<string, VariableNode> kv in m_sceneCfg.vecVariableNode)
            {
                if (kv.Value.strVarNodeName == m_strCurHilightStep)
                    bToFind = true;

                if (bToFind)
                {
                    if (((kv.Value.strVarNodeType == "Assemble") || (kv.Value.strVarNodeType == "Step")) && kv.Value.dVarCurValue < 0.5 && kv.Value.setActiveObj.Count > 0)
                    {
                        if (checkVarPreCondition(kv.Value.arrPreCondtion))
                        {
                            if (m_sceneCfg.sceneProperty.nHintPos != 3)
                            {
                                showActiveObj(kv.Value.setActiveObj);
                            }

                            if (m_strCurHilightStep == kv.Value.strVarNodeName)
                                return true;

                            m_strCurHilightStep = kv.Value.strVarNodeName;
                            return true;
                        }
                        else
                            return false;
                    }
                    else if (kv.Value.strVarNodeType == "Rotation" && kv.Value.setActiveObj.Count > 0 &&
                             kv.Value.strVarText == "")
                    {
                         if (checkVarPreCondition(kv.Value.arrPreCondtion))
                         {
                            showActiveObj(kv.Value.setActiveObj);

                            if (m_strCurHilightStep == kv.Value.strVarNodeName)
                                return true;

                            m_strCurHilightStep = kv.Value.strVarNodeName;
                            return true;
                         }
                    }
                }
            }

            return false;

        }

        public void showActiveObj(HashSet<string> _setActiveObj)
        {
            setHighlightObject(true);
            
            if (getHighlightObject())
            {
                foreach (string strActiveName in _setActiveObj)
                {
                    Debug.Log("【OutputInfo】----[showActiveObj]当前高亮的激活物体" + strActiveName);

                    GameObject hlObj = GameObject.Find(strActiveName);
                    HighlightableObject m_ho = hlObj.GetComponent<HighlightableObject>();

                    m_ho.name = strActiveName;

                    //循环往复外发光开启
                    m_ho.FlashingOn(Color.green, Color.blue, 1f);

                    //关闭循环往复外发光
                    m_ho.FlashingOff();

                    //持续外发光开启
                    m_ho.ConstantOn(Color.yellow);

                    //关闭持续外发光
                    m_ho.ConstantOff();

                    m_ho.FlashingOn(Color.green, Color.blue, 1f);
                    m_listHighObj.Add(m_ho);
                }
            }
        }

        public void offActiveObj(HashSet<string> _setActiveObj)
        {
            Debug.Log("【OutputInfo】----[offActiveObj]去掉所有的高亮");
            setHighlightObject( false );

            for (int i = 0; i < m_listHighObj.Count; i++)
            {
                m_listHighObj[i].FlashingOff();
            }
            m_listHighObj.Clear();
        }

        //根据选中的激活物体而执行相应的动作;
        public void hitVarialbeNode( string strPickObjName)
        {
            bool bFind = false;
            foreach( KeyValuePair<string,VariableNode> kv in m_sceneCfg.vecVariableNode)
            {
                foreach( string strActiveName in kv.Value.setActiveObj)
                {
                    if( strActiveName == strPickObjName)
                    {
                        offActiveObj(kv.Value.setActiveObj);
                        bool bFitAll = checkVarPreCondition(kv.Value.arrPreCondtion);
                        if( bFitAll)
                        {
                            bFind = true;
                            scrollStepVar(kv.Value);
                        }
                    }
                }

                if (bFind)
                    break;
            }
        }

        //
        public void hitVarialbeNode1(UnityEngine.Object sender,string strPickObjName)
        {
            Debug.Log("抓取物体");
            bool bFind = false;
            foreach (KeyValuePair<string, VariableNode> kv in m_sceneCfg.vecVariableNode)
            {
                foreach (string strActiveName in kv.Value.setActiveObj)
                {
                    if (strActiveName == strPickObjName)
                    {
                        offActiveObj(kv.Value.setActiveObj);
                        bool bFitAll = checkVarPreCondition(kv.Value.arrPreCondtion);
                        if (bFitAll)
                        {
                            bFind = true;
                            TDuSceneWorker worker = (TDuSceneWorker)sender;
                            GameObject activeObj = GameObject.Find(strActiveName);
                            activeObj.transform.SetParent(worker.m_controller1.transform);
                            activeObj.transform.position = new Vector3(0, 0, 0);



                            //scrollStepVar(kv.Value);
                        }
                    }
                }

                if (bFind)
                    break;
            }
        }
    }
}
